<template>
  <div class="box-all w-card">
    <div class="content-box">
      <div class="title-box">
        <span>{{ incomForm.goodsName }}</span>
        <el-button style="margin-left:auto;" @click="handleClick(1,true)">全部导出</el-button>
        <el-button type="primary" @click="handleClick(2)">批量修改状态</el-button>
      </div>
      <div class="search-box">
        <div>
          <span>卡号：</span>
          <el-input v-model="searchForm.cardNum" clearable placeholder="请输入卡号" />
        </div>
        <div>
          <span>关联订单：</span>
          <el-input v-model="searchForm.orderId" clearable placeholder="请输入关联订单" />
        </div>
        <div>
          <span>状态：</span>
          <el-select style="width:100%" v-model="searchForm.cardStatus" clearable no-data-text="请先选择类型" @change="cateChange">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div class="search-box">
        <div>
          <span>时间段：</span>
          <el-radio-group v-model="searchForm.timeType">
            <el-radio :label="1">入库时间</el-radio>
            <el-radio :label="2">有效期</el-radio>
            <el-radio :label="3">售出时间</el-radio>
          </el-radio-group>
          <el-date-picker style="margin-left:10px;" v-model="searchForm.date" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" />
        </div>
        <el-button type="primary" @click="searchHandle">查询</el-button>
        <el-button @click="resetHandle">重置</el-button>
      </div>
      <div class="table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="cardNum" label="卡号" align="center">
            <template v-slot="scope">
              {{ scope.row.cardNum || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="cardCode" label="兑换码" align="center">
            <template v-slot="scope">
              {{ scope.row.cardCode || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="cardStatus" label="状态" align="center">
            <template v-slot="scope">
              {{ getStatus(scope.row.cardStatus) || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="入库时间" align="center">
            <template v-slot="scope">
              {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="expireTime" label="有效期" align="center">
            <template v-slot="scope">
              {{ scope.row.expireTime ? getDateTime(scope.row.expireTime)[6] : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="saleTime" label="售出时间" align="center">
            <template v-slot="scope">
              {{ scope.row.saleTime ? getDateTime(scope.row.saleTime)[6] : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="orderId" label="关联订单" align="center">
            <template v-slot="scope">
              <el-link type="primary" @click="toOrderDetail(scope.row)">{{ scope.row.orderId || '' }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="operations" label="操作" align="center" width="160">
            <template v-slot="scope">
              <el-link style="font-size:14px;" type="primary" @click="editHandle(scope.row)">修改</el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-footer">
          <el-button :disabled="chooseList.length == 0" @click="handleClick(1,false)">批量导出</el-button>
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </div>
  <edit-file ref="editFileRef" @dialogClose="editDialogClose" />
  <edit-card ref="editCardRef" @dialogClose="editCardClose" />
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getWindowWidthAndHeight, warningDeal, getDateTime, BlobDownLoad, isContains } from '@/utils/utils'
import editFile from './components/editFile.vue'
import editCard from './components/editCard.vue'
import api from './api'
export default {
  components: {
    editFile,
    editCard,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    const editFileRef = ref(null)
    const editCardRef = ref(null)

    const state = reactive({
      page: 1,
      size: 10,
      total: 0,
      tableHeight: 0,
      incomForm: {},
      searchForm: {
        timeType: 1,
      },
      tableData: [],
      chooseList: [],
      statusOptions: [
        {
          value: 1,
          label: '可售',
        },
        {
          value: 2,
          label: '销售中',
        },
        {
          value: 3,
          label: '已售出',
        },
        {
          value: 4,
          label: '兑换',
        },
        {
          value: 5,
          label: '过期',
        },
        {
          value: 6,
          label: '作废',
        },
      ],
    })

    function getStatus(value) {
      let label = ''
      state.statusOptions.map(item => {
        if (item.value == value) {
          label = item.label
        }
      })
      return label
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        goodsId: state.incomForm.goodsId,
        ...state.searchForm,
        startTime: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[0].getTime() : null,
        endTime: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[1].getTime() : null,
      }
      api.cardInventoryDetail(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.records
          if (!isContains('card_see')) {
            state.tableData.map(item => {
              item.cardCode = codeEncrypt(item.cardCode)
            })
          }
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function toOrderDetail(data) {
      router.push({ path: '/dlOrder/detail', query: { sysOrderId: data.orderId } })
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        timeType: 1,
      }
      searchHandle()
    }

    function getCardNumList(list) {
      const myArr = []
      list && list.map(item => {
        myArr.push(item.cardNum)
      })
      return myArr
    }

    function handleClick(i, isAll) {
      switch (i) {
        case 1:
          //导出
          let obj = {
            goodsId: state.incomForm.goodsId,
            cardNumList: getCardNumList(state.chooseList),
          }
          if (isAll) {
            obj = {
              goodsId: state.incomForm.goodsId,
              cardNumList: null,
            }
          }
          api.cardInventoryExport({ ...obj, responseType: "blob" }).then(res => {
            const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
            BlobDownLoad(res, _fileName)
          }).catch(err => {
            console.log(err)
          })
          break
        case 2:
          //批量修改状态
          editFileRef.value.dialogShow()
          break
      }
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function editDialogClose() {
      getTableData()
    }

    function editCardClose() {
      getTableData()
    }

    function editHandle(data) {
      editCardRef.value.dialogShow(data)
    }

    function codeEncrypt(code = '') {
      let myCode = ''
      myCode = code.slice(0, 4) + '******'
      return myCode
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 350
      state.incomForm = route.query
      getTableData()
    })

    return {
      ...toRefs(state),
      editFileRef,
      editCardRef,
      handleSelectionChange,
      getDateTime,
      getStatus,
      toOrderDetail,
      searchHandle,
      resetHandle,
      handleClick,
      handleCurrentChange,
      handleSizeChange,
      editDialogClose,
      editCardClose,
      editHandle,
      isContains,
      codeEncrypt,
    }
  }
}
</script>

<style lang="scss" scoped>
.box-all {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .content-box {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;
    padding: 20px;
    .title-box {
      display: flex;
      align-items: center;
      > span {
        font-size: 16px;
        font-weight: bold;
      }
    }
    .search-box {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-top: 20px;
      > div {
        display: flex;
        align-items: center;
        font-size: 14px;
        > span {
          flex-shrink: 0;
        }
      }
    }
    .table-box {
      margin-top: 20px;
      .table-footer {
        margin-top: 20px;
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>